package com.openasv;

import ioio.lib.api.IOIO;
import ioio.lib.api.IOIOFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.openasv.act.IoioController;

import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;


public class OpenASVActivity extends Activity implements LocationListener,
		SeekBar.OnSeekBarChangeListener, OnClickListener {

	protected Thread stateUpdater = null;
	protected LocationManager manager;
	protected IoioController controller = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		((SeekBar) findViewById(R.id.leftSlider)).setEnabled(false);
		((SeekBar) findViewById(R.id.rightSlider)).setEnabled(false);
		((ToggleButton) findViewById(R.id.motorsToggle)).setEnabled(false);
		try {
			String ip = "127.0.0.1";
			try {
				for (Enumeration<NetworkInterface> en = NetworkInterface
						.getNetworkInterfaces(); en.hasMoreElements();) {
					NetworkInterface intf = en.nextElement();
					for (Enumeration<InetAddress> enumIpAddr = intf
							.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()) {
							ip = inetAddress.getHostAddress();
						}
					}
				}
			} catch (SocketException ex) {
				ex.printStackTrace();
			}

			((TextView) findViewById(R.id.ipText)).setText("IP: "+ ip);
		} catch (Exception e) {
			e.printStackTrace();
		}

		manager = (LocationManager) getSystemService(LOCATION_SERVICE);
		try {
			manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15000,
					1, this);
			((CheckBox) findViewById(R.id.gpsCheck)).setChecked(true);
			((CheckBox) findViewById(R.id.gpsCheck)).setClickable(false);

		} catch (Exception e) {
			e.printStackTrace();
			Log.e("OpenASV", "No location provider has been found.");
		}

		new Thread() {
			public void run() {
				try {
					IOIO ioio = IOIOFactory.create();
					Log.i("OpenASV", "trying to connect to ioio board...");
					ioio.waitForConnect();
					((CheckBox) findViewById(R.id.ioioCheck)).setChecked(true);
					((CheckBox) findViewById(R.id.ioioCheck))
							.setClickable(false);

					((SeekBar) findViewById(R.id.leftSlider))
							.setClickable(true);
					((SeekBar) findViewById(R.id.rightSlider))
							.setClickable(true);
					((ToggleButton) findViewById(R.id.motorsToggle))
							.setClickable(true);
					controller = new IoioController(ioio, true);
				} catch (Exception e) {
					e.printStackTrace();
					Log.e("OpenASV", "Error connecting to IOIO board.");
				}

			};
		}.start();

		((SeekBar) findViewById(R.id.leftSlider))
				.setOnSeekBarChangeListener(this);
		((SeekBar) findViewById(R.id.rightSlider))
				.setOnSeekBarChangeListener(this);
		((ToggleButton) findViewById(R.id.motorsToggle))
				.setOnClickListener(this);
	}

	@Override
	protected void onDestroy() {
		manager.removeUpdates(this);
		super.onDestroy();
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {

		if (controller == null)
			return;

		ToggleButton btn = (ToggleButton) findViewById(R.id.motorsToggle);
		if (!btn.isSelected())
			return;

		if (seekBar == findViewById(R.id.leftSlider)) {
			System.out.println("left: " + progress);
			controller.setLeftThruster(progress / 100.0f);
		} else if (seekBar == findViewById(R.id.rightSlider)) {
			System.out.println("right: " + progress);
			controller.setRightThruster(progress / 100.0f);
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {

	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {

	}

	@Override
	public void onClick(View v) {
		if (v == ((ToggleButton) findViewById(R.id.motorsToggle))) {
			if (controller == null)
				return;

			if (((ToggleButton) findViewById(R.id.motorsToggle)).isChecked()) {
				System.out.println("Motors on!");
			} else {
				System.out.println("Motors off!");
				controller.setLeftThruster(0);
				controller.setRightThruster(0);
			}
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		/*State st = new State(location);
		Log.d("OpenASV", st.toString());
		StateLogger.logState(st);*/
	}

	@Override
	public void onProviderDisabled(String provider) {
		Log.i("OpenASV", provider + " location provider has been disabled");
	}

	@Override
	public void onProviderEnabled(String provider) {
		Log.i("OpenASV", provider + " location provider has been enabled");
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.i("OpenASV", provider + " status changed to " + status);
	}
}